package org.example.controller;


import org.example.entity.Demo;
import org.example.service.IDemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author
 * @since 2024-06-13
 */
@RestController
@RequestMapping("/demo")
public class DemoController {
    @Autowired
    IDemoService iDemoService;
    @Value("${upload.path}")
    String path1;
    @GetMapping("/test")
    public Map<String, String> test() {
        Map<String, String> res = new HashMap<>();
        res.put("id","1");
        System.out.println("==============res=>"+res);
        return res;
    }
    @GetMapping("/test1")
    public List<Demo> test1() {
        List res = iDemoService.listMaps();
        System.out.println("==============res=>"+res);
        return res;
    }
    @GetMapping("/test2")
    public List<Demo> test2() {
        List res = iDemoService.listAllData();
        System.out.println("==============res=>"+res);
        return res;
    }
    @GetMapping("/test3")
    public List<Demo> test3(HttpServletRequest req) {
        System.out.println("------req--->"+req.getParameter("a"));
        List res = iDemoService.listAllDataWithOrg();
        System.out.println("==============res=>"+res);
        return res;
    }
    @PostMapping("/test4")
    public List<Demo> test4(HttpServletRequest req) {
        System.out.println("------req-getParameter-->"+req.getParameter("a"));
        List res = iDemoService.listAllDataWithOrg();
        System.out.println("==============res=>"+res);
        return res;
    }
    @PostMapping("/test5")
    public List<Demo> test5(@RequestBody Map<String, String> req) {
        System.out.println("------req--->"+req);
        System.out.println("------req--->"+req.get("a"));
        List res = iDemoService.listAllDataWithOrg();
        System.out.println("==============res=>"+res);
        return res;
    }
    @GetMapping("/delete")
    public boolean delete(HttpServletRequest req) {
//        System.out.println("------req--->"+req);
        iDemoService.deleteAllData();
        return true;
    }

    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "文件为空，请选择一个文件上传";
        }

        String fileName = file.getOriginalFilename();
        String filePath = path1;
        File dest = new File(filePath + fileName);

        try {
            file.transferTo(dest);
            return "文件上传成功";
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "文件上传失败";
    }
}
